package com.rabbitmq.spring.controller;

import com.rabbitmq.client.BuiltinExchangeType;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.rabbitmq.common.constants.CommonConstants.SPRING_EXCHANGE_NAME_PREFIX;
import static com.rabbitmq.common.constants.CommonConstants.TOPIC_ROUTING_KEYS;

/**
 * @author
 * @Describe 功能描述
 * @date
 */
@RestController
public class RabbitmqNotesController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("send")
    public void send() {
        for (int i = 1; i <= 3; i++) {
            String routingKey = TOPIC_ROUTING_KEYS[(i - 1) % 3];
            rabbitTemplate.convertAndSend(SPRING_EXCHANGE_NAME_PREFIX + BuiltinExchangeType.TOPIC.getType() + "_publishTopicQueueTtlDeadLetterx",
                    routingKey, "publishTopicQueueTtlDeadLetterx 第" + i + "次发送消息, cur routingKey is " + routingKey);
        }
    }

    @GetMapping("sendSingleMsgTtl")
    public void sendSingleMsgTtl() {
        for (int i = 1; i <= 3; i++) {
            String routingKey = TOPIC_ROUTING_KEYS[(i - 1) % 3];
            MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    // 设置消息过期属性10s
                    message.getMessageProperties().setExpiration("10000");
                    return message;
                }
            };
            rabbitTemplate.convertAndSend(SPRING_EXCHANGE_NAME_PREFIX + BuiltinExchangeType.TOPIC.getType() + "_publishTopicSingleMsgTtlDeadLetterx",
                    routingKey, "publishTopicSingleMsgTtlDeadLetterx 第" + i + "次发送消息, cur routingKey is " + routingKey, messagePostProcessor);
        }
    }

}
